package com.xh.one2one.lesson.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xh.bussiness.resource.model.Material;
import com.xh.bussiness.resource.service.IMaterialService;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzScheduleRequest;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzStudentInfoRequest;
import com.xh.bussiness.thirdapi.xinzhou.model.XzRemainContactHour;
import com.xh.bussiness.thirdapi.xinzhou.model.XzSchedule;
import com.xh.bussiness.thirdapi.xinzhou.service.IXinzhouTmsService;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.util.DateUtils;
import com.xh.one2one.base.bean.request.StageReportRequest;
import com.xh.one2one.base.service.IStageReportService;
import com.xh.one2one.lesson.bean.dto.*;
import com.xh.one2one.lesson.bean.request.LessonSummaryDetailsRequest;
import com.xh.one2one.lesson.bean.request.LessonSummaryRequest;
import com.xh.one2one.lesson.model.*;
import com.xh.one2one.lesson.dao.LessonSummaryMapper;
import com.xh.one2one.lesson.service.*;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.one2one.teachHandout.bean.request.TeachTimesHandoutRelationRequest;
import com.xh.one2one.teachHandout.model.TeachTimesHandoutRelation;
import com.xh.one2one.teachHandout.service.ITeachTimesHandoutRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

/**
 * <p>
 * 教学总结 服务实现类
 * </p>
 *
 * @author TW
 * @since 2021-05-06
 */
@Service
public class LessonSummaryServiceImpl extends BaseServiceImpl<LessonSummaryMapper, LessonSummary> implements ILessonSummaryService {

    @Autowired
    private ILessonInfoService lessonInfoService;
    @Autowired
    private IXinzhouTmsService xinzhouTmsService;
    @Autowired
    private ILessonSummaryDetailsService lessonSummaryDetailsService;
    @Autowired
    private ILessonTimesService lessonTimesService;
    @Autowired
    private ITeachTimesHandoutRelationService teachTimesHandoutRelationService;
    @Autowired
    private IMaterialService materialService;
    @Autowired
    private IStageReportService stageReportService;
    @Autowired
    private ILessonEntranceExamService entranceExamService;
    @Autowired
    private ILessonPlanService lessonPlanService;
    @Autowired
    private IQuestionService questionService;

    @Override
    public XhPage queryLessonSummaryPage(XhPage page, LessonSummaryRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonSummary>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public List queryLessonSummary(LessonSummaryRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonSummary>();
        //拼装条件
        qw=prepareParams(bean, qw);


        return this.dao.selectList(qw);
    }

    @Override
    public List queryStudentSummary(LessonSummaryRequest bean) {
        LessonInfo lessonInfo = lessonInfoService.getById(bean.getLessonId());
        //查询排课学生
//        XzScheduleRequest scheduleRequest = new XzScheduleRequest();
//        if(1 == bean.getSearchType()){
//            scheduleRequest.setStudentId(lessonInfo.getLessonId());
//            scheduleRequest.setScheduleInstanceOTOType("一对一");
//        }else{
//            scheduleRequest.setGroupId(lessonInfo.getLessonId());
//            scheduleRequest.setScheduleInstanceOTOType("一对六");
//        }

//        List<XzSchedule>  schedules = xinzhouTmsService.querySchedule(scheduleRequest);

//        Date startTime = lessonInfo.getStartTime();
//        List<XzSchedule> stuList = schedules.stream().filter(schedule -> schedule.getClassDateTimeFrom().equals(startTime)).collect(Collectors.toList());
//        stuList = stuList.stream().collect(collectingAndThen(toCollection(
//                () -> new TreeSet<>(
//                        Comparator.comparing(XzSchedule::getScheduleInstanceOTOId))),ArrayList::new));
//        if(CollectionUtils.isEmpty(stuList)){
//            return Collections.EMPTY_LIST;
//        }

//        stuList = stuList.stream().sorted(Comparator.comparing(XzSchedule::getCreateTime)).collect(Collectors.toList());

        List<XzSchedule> stuList = new ArrayList<>();
        LessonPlan lessonPlan = lessonPlanService.getById(bean.getLessonThirdId());
        String studentIds = lessonPlan.getStudentIds();
        String studentNames = lessonPlan.getStudentNames();
        if(StringUtils.isNotEmpty(studentIds)){
            List<String> ids = Arrays.asList(studentIds.split(","));
            List<String> names = Arrays.asList(studentNames.split(","));
            for (int i = 0; i < ids.size(); i++) {
                XzSchedule schedule = new XzSchedule();
                schedule.setStudentId(ids.get(i));
                schedule.setStudentName(names.get(i));
                stuList.add(schedule);
            }
        }
        List<LessonSummary>   retList = new ArrayList();
        for (int i = 0; i < stuList.size(); i++) {
            XzSchedule xzSchedule = stuList.get(i);
            LessonSummary summary = new LessonSummary();
            summary.setLessonId(lessonInfo.getLessonId());
            summary.setStudentId(xzSchedule.getStudentId());
            summary.setLessonThirdId(bean.getLessonThirdId());
            summary.setStudentName(xzSchedule.getStudentName());
            LessonSummaryRequest request = new LessonSummaryRequest();
//            request.setLessonId(bean.getLessonId());
            request.setLessonThirdId(bean.getLessonThirdId());
            request.setStudentId(xzSchedule.getStudentId());
            LessonSummary lessonSummary = queryOne(request);
            if(null != lessonSummary){
                BeanUtils.copyProperties(lessonSummary,summary);

                QueryWrapper<LessonSummaryDetails> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("lesson_third_id",bean.getLessonThirdId());
                queryWrapper.eq("student_id",xzSchedule.getStudentId());
                queryWrapper.eq("correct",0);
                queryWrapper.groupBy("question_id");
                List<LessonSummaryDetails> lessonSummaryDetails = lessonSummaryDetailsService.queryByCondition(queryWrapper);
                Integer count = 0;
                if(!CollectionUtils.isEmpty(lessonSummaryDetails)){
                    count = lessonSummaryDetails.size();
                }
                summary.setWrongTopicTotal(count);
            }else{
                summary.setStatus(0);
                summary.setWrongTopicTotal(0);
                this.insert(summary);
            }

            retList.add(summary);
        }
        return retList;
    }

    @Override
    public LessonSummaryDto queryLast(LessonSummaryRequest bean) {
        List<LessonSummary> list = queryLessonSummary(bean);
        LessonSummaryDto dto = new LessonSummaryDto();
        if(!CollectionUtils.isEmpty(list)){
            //最近一次教学总结
            LessonSummary summary = list.get(0);
            BeanUtils.copyProperties(summary,dto);

            Integer entranceScore = summary.getEntranceScore();
            Integer practiceScore = summary.getPracticeScore();
            Integer homeworkScore = summary.getLastHomeworkScore();

            int entranceScoreSum = list.stream().filter(lessonSummary ->null != lessonSummary.getEntranceScore()).mapToInt(LessonSummary::getEntranceScore).sum();
            int practiceScoreSum = list.stream().filter(lessonSummary ->null != lessonSummary.getPracticeScore()).mapToInt(LessonSummary::getPracticeScore).sum();
            int homeworkScoreSum = list.stream().filter(lessonSummary ->null != lessonSummary.getLastHomeworkScore()).mapToInt(LessonSummary::getLastHomeworkScore).sum();


            int size = list.size();
            //上一次教学总结
            LessonSummary old = null;
            boolean  hasPre  = size > 1;
            if(hasPre){
                old = list.get(1);
            }else{
                old = new LessonSummary();
                old.setEntranceScore(0);
                old.setPracticeScore(0);
                old.setLastHomeworkScore(0);
            }

            if(null == entranceScore){
                entranceScore = 0;
            }
            if(null == practiceScore){
                practiceScore = 0;
            }
            if(null == homeworkScore){
                homeworkScore = 0;
            }
            dto.setMoreEntranceScore(entranceScore - (null == old.getEntranceScore()?0:old.getEntranceScore()));
            dto.setMorePracticeScore(practiceScore - (null == old.getPracticeScore()?0:old.getPracticeScore()));
            dto.setMoreHomeworkScore(homeworkScore - (null == old.getLastHomeworkScore()? 0:old.getLastHomeworkScore()));

            int currAvgEntranceScore = entranceScoreSum / size;
            int oldAvgEntranceScore = hasPre ? (entranceScoreSum - entranceScore) / (size - 1) : 0;
            int currAvgPracticeScore = practiceScoreSum / size;
            int oldAvgPracticeScore = hasPre ?(practiceScoreSum - practiceScore) / (size - 1) : 0;
            int currAvgHomeworkScore = homeworkScoreSum / size;
            int oldAvgHomeworkScore= hasPre ?(homeworkScoreSum - homeworkScore) / (size - 1) : 0;

            dto.setAvgEntranceScore(currAvgEntranceScore - oldAvgEntranceScore);
            dto.setAvgPracticeScore(currAvgPracticeScore - oldAvgPracticeScore);
            dto.setAvgHomeworkScore(currAvgHomeworkScore - oldAvgHomeworkScore);

            //查询本节课错题和总错题数
            String lessonThirdId = summary.getLessonThirdId();
            String studentId = bean.getStudentId();
            QueryWrapper<LessonSummaryDetails> qw = new QueryWrapper<>();
            qw.eq("student_id",studentId);
            qw.eq("correct",0);
            qw.eq("lesson_type",bean.getSearchType());
            Integer  totalCount = lessonSummaryDetailsService.selectCount(qw);
            qw.eq("lesson_third_id",lessonThirdId);
            Integer currentCount = lessonSummaryDetailsService.selectCount(qw);

            dto.setWrongTopicTotal(totalCount);
            dto.setCurrentCount(currentCount);
        }

        return dto;
    }

    @Override
    public List querySummaryByStudentId(LessonSummaryRequest bean) {
        List<LessonSummaryTimeDto> ret = new ArrayList<>();
        List<LessonSummary> list = queryLessonSummary(bean);
        if(!CollectionUtils.isEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                LessonSummaryTimeDto dto = new LessonSummaryTimeDto();
                LessonSummary summary = list.get(i);
                BeanUtils.copyProperties(summary,dto);
                String id = summary.getLessonId();
                LessonInfo lessonInfo = lessonInfoService.getById(id);

                Date startTime = lessonInfo.getStartTime();
                Date endTime = lessonInfo.getEndTime();
                String startStr = DateUtils.format(startTime, "yyyy-MM-dd HH:mm");
                String endStr = DateUtils.format(endTime, "yyyy-MM-dd HH:mm");
                String classTime = startStr +" -"+ endStr.substring(10);
                dto.setClassTime(classTime);

                String lessonId = lessonInfo.getLessonId();
                if(1 == lessonInfo.getType()){
                    lessonId = lessonInfo.getContractId();
                }
                String thirdId = lessonInfo.getThirdId();
                QueryWrapper<LessonTimes> lessonTimesQueryWrapper = new QueryWrapper<>();
                lessonTimesQueryWrapper.eq("lesson_id",lessonId);
                lessonTimesQueryWrapper.eq("lesson_third_id",thirdId);
                LessonTimes lessonTimes = lessonTimesService.selectFirst(lessonTimesQueryWrapper);
                if(null != lessonTimes){
                    dto.setTimeName(lessonTimes.getIndexName());
                }
                QueryWrapper<LessonSummaryDetails> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("lesson_third_id",thirdId);
                queryWrapper.eq("student_id",bean.getStudentId());
                queryWrapper.eq("correct",0);
                Integer count = lessonSummaryDetailsService.selectCount(queryWrapper);
                dto.setCurrentCount(count);
                ret.add(dto);
            }
        }
        return ret;
    }

    @Override
    public List querySummaryToReport(LessonSummaryRequest bean) {
        List<LessonHandoutDto> ret = new ArrayList<>();
        List<LessonSummary> list = queryLessonSummary(bean);
        if(!CollectionUtils.isEmpty(list)){
            List<String> ids = list.stream().map(LessonSummary::getLessonId).collect(Collectors.toList());
            QueryWrapper<LessonInfo> lessonInfoQueryWrapper = new QueryWrapper<>();
            lessonInfoQueryWrapper.in("id",ids);
            lessonInfoQueryWrapper.orderByAsc("create_time");
            List<LessonInfo> lessonInfos = lessonInfoService.queryByCondition(lessonInfoQueryWrapper);
            for (int i = 0; i < lessonInfos.size(); i++) {
                LessonInfo lessonInfo = lessonInfos.get(i);
                LessonHandoutDto dto = new LessonHandoutDto();
                BeanUtils.copyProperties(lessonInfo,dto);

                String infoId = lessonInfo.getId();
                String thirdId = lessonInfo.getThirdId();
                String lessonId = lessonInfo.getLessonId();
                if(1 == lessonInfo.getType()){
                    lessonId = lessonInfo.getContractId();
                }
                List<TeachTimesHandoutRelation> timesHandoutRelation = lessonTimesService.getTimesHandoutRelations(null,infoId, thirdId, lessonId);
                if(!CollectionUtils.isEmpty(timesHandoutRelation)){
                    String handoutId = timesHandoutRelation.get(0).getHandoutId();
                    Material material = materialService.getById(handoutId);
                    dto.setHandoutId(material.getId());
                    dto.setHandoutName(material.getFileName());
                    ret.add(dto);
                }
            }
        }
        return ret;
    }

    @Override
    public List queryStudentReport(LessonSummaryRequest bean) {
        List<StudentLessonReportDto> ret = new ArrayList<>();
        XzScheduleRequest request = new XzScheduleRequest();
        request.setStudentId(bean.getStudentId());
        request.setClassDateTimeFrom_begin(bean.getStartDate());
        request.setClassDateTimeFrom_end(bean.getEndDate());
        //请求新舟远程数据
        List<XzSchedule> schedule = xinzhouTmsService.querySchedule(request);
        Iterator<XzSchedule> iterator = schedule.iterator();
        while (iterator.hasNext()){
            StudentLessonReportDto studentLessonReportDto = new StudentLessonReportDto();
            XzSchedule xzSchedule = iterator.next();
            String scheduleInstanceOTOId = xzSchedule.getScheduleInstanceOTOId();
            LessonInfo lessonInfo = lessonInfoService.getByThirdId(scheduleInstanceOTOId);
            if(null == lessonInfo){
                iterator.remove();
                continue;
            }
            String lessonInfoId = lessonInfo.getId();
            String lessonId = lessonInfo.getLessonId();
            String thirdId = lessonInfo.getThirdId();
            if(1 == lessonInfo.getType()){
                lessonId = lessonInfo.getContractId();
            }
            studentLessonReportDto.setContractId(lessonInfo.getContractId());
            studentLessonReportDto.setLessonType(lessonInfo.getType());
            QueryWrapper<LessonTimes> lessonTimesQueryWrapper = new QueryWrapper<>();
            lessonTimesQueryWrapper.eq("lesson_id",lessonId);
            lessonTimesQueryWrapper.eq("lesson_third_id",scheduleInstanceOTOId);
            //获取课次
            LessonTimes lessonTimes = lessonTimesService.selectFirst(lessonTimesQueryWrapper);
            if(null == lessonTimes){
                //如果课次为空则获取当前课的讲义 以讲义名称做学生报告名称
                List<TeachTimesHandoutRelation> timesHandoutRelation = lessonTimesService.getTimesHandoutRelations(null,lessonInfoId, thirdId, lessonId);
                if(CollectionUtils.isEmpty(timesHandoutRelation)){
                    iterator.remove();
                    continue;
                }else {
                    String handoutId = timesHandoutRelation.get(0).getHandoutId();
                    Material material = materialService.getById(handoutId);
//                    dto.setHandoutId(material.getId());
                    studentLessonReportDto.setTitle(material.getFileName());
                }
            }else{
                studentLessonReportDto.setTitle(lessonTimes.getIndexName());
            }

            Date startTime = lessonInfo.getStartTime();
            Date endTime = lessonInfo.getEndTime();
            String startStr = DateUtils.format(startTime, "yyyy-MM-dd HH:mm");
            String endStr = DateUtils.format(endTime, "yyyy-MM-dd HH:mm");
            String classTime = startStr +" -"+ endStr.substring(10);
            String month = DateUtils.format(startTime, "MM");

            studentLessonReportDto.setMonth(month);
            studentLessonReportDto.setClassTime(classTime);
            studentLessonReportDto.setLessonId(lessonId);
            studentLessonReportDto.setLessonThirdId(thirdId);
            studentLessonReportDto.setLessonInfoId(lessonInfoId);

            QueryWrapper<LessonSummaryDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("lesson_third_id",thirdId);
            queryWrapper.eq("student_id",bean.getStudentId());
            List<LessonSummaryDetails> details = lessonSummaryDetailsService.queryByCondition(queryWrapper);
            if(CollectionUtils.isEmpty(details)){
                studentLessonReportDto.setWrongCount(0);
                studentLessonReportDto.setSuccessRate(0);
            }else{
                long countWrong = details.stream().filter(data -> 0 == data.getCorrect()).count();
                long countRight = details.stream().filter(data -> 1 == data.getCorrect()).count();

                studentLessonReportDto.setWrongCount(countWrong);

                NumberFormat numberFormat = NumberFormat.getInstance();
                numberFormat.setMaximumFractionDigits(0);
                String successRate = numberFormat.format((double)countRight/(double)details.size()*100);
                studentLessonReportDto.setSuccessRate(Long.valueOf(successRate));
            }

            bean.setLessonThirdId(thirdId);
            bean.setStatus(1);
            List<LessonSummary> lessonSummarys = queryLessonSummary(bean);
//            if(CollectionUtils.isEmpty(lessonSummarys)){
//                studentLessonReportDto.setChecked(0);
//            }else{
//                studentLessonReportDto.setChecked(1);
//            }
            if(!CollectionUtils.isEmpty(lessonSummarys)){
                ret.add(studentLessonReportDto);
            }
        }

        return ret;
    }

    @Override
    public StudentReportStatisDto queryStudentReportStatis(LessonSummaryRequest bean) throws Exception {
        XzStudentInfoRequest studentInfo = new XzStudentInfoRequest();
        studentInfo.setStudentId(bean.getStudentId());
        List<XzRemainContactHour> contactHour = xinzhouTmsService.queryStudentRemainContactHour(studentInfo);
//        double remainHour = contactHour.stream().mapToDouble(XzRemainContactHour::getRemainCount).sum();
        double remainHour = contactHour.stream().filter(xzRemainContactHour -> "一对一".equals(xzRemainContactHour.getContractType()))
                .mapToDouble(XzRemainContactHour::getRemainCount).sum();

        List<LessonSummary> list = queryLessonSummary(bean);
        Integer countCourse = CollectionUtils.isEmpty(list) ? 0 : list.size();

        StageReportRequest stageReportRequest = new StageReportRequest();
        stageReportRequest.setStudentId(bean.getStudentId());
        List stageList = stageReportService.queryStageReport(stageReportRequest);
        Integer countStage = CollectionUtils.isEmpty(stageList) ? 0 : stageList.size();

        StudentReportStatisDto dto = new StudentReportStatisDto();
        dto.setRemainHour(remainHour);
        dto.setCountCourse(countCourse);
        dto.setCountStage(countStage);

        return dto;
    }

    @Override
    public LessonSummary queryOne(LessonSummaryRequest bean) {
        QueryWrapper qw=new QueryWrapper<LessonSummary>();
        //拼装条件
        qw=prepareParams(bean, qw);
        return this.dao.selectOne(qw);
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(LessonSummaryRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if(StringUtils.isNotEmpty(bean.getLessonId())){
            qw.eq("lesson_id",bean.getLessonId());
        }
        if(StringUtils.isNotEmpty(bean.getLessonThirdId())){
            qw.eq("lesson_third_id",bean.getLessonThirdId());
        }
        if(StringUtils.isNotEmpty(bean.getIndexId())){
            qw.eq("index_id",bean.getIndexId());
        }
        if(StringUtils.isNotEmpty(bean.getStudentId())){
            qw.eq("student_id",bean.getStudentId());
        }
        if(StringUtils.isNotEmpty( bean.getCreatorId())){
            qw.eq("creator_id",bean.getCreatorId());
        }
        if(StringUtils.isNotEmpty( bean.getContractId())){
            qw.eq("contract_id",bean.getContractId());
        }
        if(null != bean.getStatus()){
            qw.eq("status",bean.getStatus());
        }
        if(null != bean.getOrderType()){
            if(1 == bean.getOrderType()){
                qw.orderByDesc("create_time");
            }
        }
        return qw;
    }


    @Override
    public LessonSummary queryStudentClassReport(LessonSummaryRequest bean) {
        QueryWrapper<LessonSummary> qw = new QueryWrapper<>();
        qw.eq("student_id",bean.getStudentId());
        qw.eq("lesson_third_id",bean.getLessonThirdId());
        LessonSummary summary = this.dao.selectOne(qw);
        return summary;
    }

    /**
     * 一对一备课修改上节课课后练习分数
     * @author 赵文博
     * @date 2021/6/8 15:12
     * @param summaryRequest
     * @return boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLessonSummary(LessonSummaryRequest summaryRequest) {
        //修改本节课的上节课分数
        LessonSummary lessonSummary = new LessonSummary();
        BeanUtils.copyProperties(summaryRequest,lessonSummary);
        boolean flag = this.update(lessonSummary);

        //修改上节课的课后作业分数
        if(summaryRequest.getLastHomeworkScore()!=null){
            QueryWrapper<LessonInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("contract_id",summaryRequest.getContractId());
            queryWrapper.orderByDesc("start_time");
            List<LessonInfo> lessonInfos =lessonInfoService.selectList(queryWrapper,LessonInfo.class);
            for(int i = 0;i<lessonInfos.size();i++){
                LessonInfo lessonInfo = lessonInfos.get(i);
                if(summaryRequest.getLessonThirdId().equals(lessonInfo.getThirdId())){
                    int j = i+1;
                    if(j<lessonInfos.size()){
                        String thirdId = lessonInfos.get(j).getThirdId();
                        UpdateWrapper<LessonSummary> updateWrapper = new UpdateWrapper();
                        updateWrapper.set("homework_score",summaryRequest.getLastHomeworkScore());
                        updateWrapper.eq("lesson_third_id",thirdId);
                        flag = this.dao.update(new LessonSummary(),updateWrapper)>0;
                    }
                }
            }
        }
        return flag ;
    }

    @Override
    public List<LessonSummaryDto> queryClassroomPractice(LessonSummaryRequest summaryRequest) {
        //题目总数
        String lessonThirdId = summaryRequest.getLessonThirdId();
        Integer entranceQuestionCount = lessonSummaryDetailsService.selectQuestionCountByType(lessonThirdId,1);
        Integer practiceQuestionCount = lessonSummaryDetailsService.selectQuestionCountByType(lessonThirdId,2);
        //查询所有学生
//        QueryWrapper<LessonSummary> lessonSummaryQW = new QueryWrapper<>();
//        lessonSummaryQW.select("student_id");
//        lessonSummaryQW.eq("lesson_third_id",summaryRequest.getLessonThirdId());
//        List<LessonSummary> lessonSummaries = this.selectList(lessonSummaryQW,LessonSummary.class);
        List<String> studentIds = this.dao.selectStudentIdByLessonThirdId(summaryRequest.getLessonThirdId());
        List<LessonSummaryDto> lessonSummaryDtoList = new ArrayList<>();

        //获取lessTimeId
        QueryWrapper qw = new QueryWrapper<LessonTimes>();
        qw.eq("lesson_id", summaryRequest.getLessonId());
        qw.eq("lesson_third_id", lessonThirdId);
        qw.orderByAsc("sort_num");
        LessonTimesDto lessonTimesDto = lessonTimesService.selectFirst(qw, LessonTimesDto.class);
        String handoutId = "";
        String paperId = "";
        String lessonTimeId ="";

        if(lessonTimesDto!=null){
            lessonTimeId = lessonTimesDto.getId();
            //获取讲义id
            handoutId = getHandoutId(lessonTimeId,lessonThirdId);
            //获取试卷id
            paperId = getEntranceExamPaperId(lessonTimeId);
        }

        for(String studentId : studentIds){
            //查询当前学生进门考和课中练习错题数
            LessonSummaryDto lessonSummaryDto = this.dao.selectErrorQuestionCount(lessonThirdId,studentId);
            lessonSummaryDto.setEntranceQuestionCount(entranceQuestionCount);//进门考试题总数
            lessonSummaryDto.setPracticeQuestionCount(practiceQuestionCount);//课中练习试题总数
            lessonSummaryDto.setPaperId(paperId);
            lessonSummaryDto.setHandoutId(handoutId);
            lessonSummaryDto.setLessonTimeId(lessonTimeId);
            if(studentId.equals(summaryRequest.getStudentId())){
                lessonSummaryDtoList.add(0,lessonSummaryDto);
            }else{
                lessonSummaryDtoList.add(lessonSummaryDto);
            }
        }
        return lessonSummaryDtoList;
    }

    /**
     * 查询小组课评价
     * @author 赵文博
     * @date 2021/6/16 16:06
     * @param bean
     * @return com.xh.one2one.lesson.bean.dto.LessonInfoDto
     **/
    @Override
    public LessonInfoDto queryGroupClassEvaluate(LessonInfo bean) {
        return this.dao.queryGroupClassEvaluate(bean);
    }

    /**
     * 查询讲义id
     * @author 赵文博
     * @date 2021/6/23 15:39
     * @param lessonTimeId
     * @param lessonThirdId
     * @return void
     **/
    private String getHandoutId(String lessonTimeId,String lessonThirdId){
        TeachTimesHandoutRelationRequest relationRequest = new TeachTimesHandoutRelationRequest();
        relationRequest.setIndexId(lessonTimeId);
        List<TeachTimesHandoutRelation> timesHandoutRelations = teachTimesHandoutRelationService.queryList(relationRequest);
        if(timesHandoutRelations.size()==0){
            relationRequest = new TeachTimesHandoutRelationRequest();
            LessonInfo lessonInfo = lessonInfoService.getByThirdId(lessonThirdId);
            relationRequest.setIndexId(lessonInfo.getId());
            timesHandoutRelations = teachTimesHandoutRelationService.queryList(relationRequest);
        }
        if(timesHandoutRelations.size()>0){
           return timesHandoutRelations.get(0).getHandoutId();
        }
        return null;
    }

    /**
     * 获取进门考试卷id
     * @author 赵文博
     * @date 2021/6/23 15:43
     * @param lessonTimeId
     * @return void
     **/
    private String getEntranceExamPaperId(String lessonTimeId){
        QueryWrapper<LessonEntranceExam> queryWrapper = new QueryWrapper();
        queryWrapper.eq("lesson_time_id",lessonTimeId);
        LessonEntranceExam entranceExam = entranceExamService.selectFirst(queryWrapper);
        if(entranceExam!=null){
            return entranceExam.getPaperId();
        }

        return null;
    }

    @Override
    public boolean updateScore(LessonSummary lessonSummary) {
        if(StringUtils.isEmpty(lessonSummary.getId())){
            return this.insert(lessonSummary);
        }
        return this.dao.updateLessonSummary(lessonSummary)>0;
    }

    @Override
    public XhPage<LessonSummaryDetails> queryStudentWrongQuestions(XhPage<LessonSummaryDto> page, LessonSummaryDetailsRequest bean) {
//        QueryWrapper<LessonSummaryDetails> queryWrapper = new QueryWrapper();
//        queryWrapper.le("student_id",studentId);
//        if(StringUtils.isNotEmpty(startDate)){
//            queryWrapper.ge("create_time", DateUtils.getDateStart(DateUtils.parseDate(startDate, "yyyy-MM-dd")));
//        }
//        if(StringUtils.isNotEmpty(endDate)){
//            queryWrapper.le("create_time", DateUtils.getDateStart(DateUtils.parseDate(endDate, "yyyy-MM-dd")));
//        }
        XhPage<LessonSummaryDetails> pageR = lessonSummaryDetailsService.queryLessonSummaryDetailsPage(page, bean);
//        List<String>  quesIds = details.stream().map(LessonSummaryDetails :: getQuestionId).distinct().collect(toList());
        List<LessonSummaryDetails> details =  pageR.getRecords();
        if(!details.isEmpty()){
            for (LessonSummaryDetails record : details) {
                QuestionDto questionDto = questionService.getQuestion(record.getQuestionId(),null,true,true,false,true,false);
                record.setQuestionDto(questionDto);
            }
        }
        return pageR;
    }
}
